// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.neuronbit.businessflow.intellij.editor.swing.editor.propertyInspector.editors;

import com.neuronbit.businessflow.intellij.editor.swing.editor.propertyInspector.InplaceContext;
import com.neuronbit.businessflow.intellij.editor.swing.editor.propertyInspector.PropertyEditor;
import com.neuronbit.businessflow.intellij.editor.swing.editor.RadComponent;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**
 * The type Abstract text field editor.
 *
 * @param <V> the type parameter
 */
public abstract class AbstractTextFieldEditor<V> extends PropertyEditor<V> {
    /**
     * The My tf.
     */
    protected final JTextField myTf;

    /**
     * Instantiates a new Abstract text field editor.
     */
    protected AbstractTextFieldEditor() {
    myTf = new JTextField();
    myTf.addActionListener(new MyActionListener());
  }

  @Override
  public void updateUI() {
    SwingUtilities.updateComponentTreeUI(myTf);
  }

    /**
     * Sets value from component.
     *
     * @param component the component
     * @param value     the value
     */
    protected void setValueFromComponent(RadComponent component, V value) {
    myTf.setText(value == null ? "" : value.toString());
  }

  @Override
  public JComponent getComponent(final RadComponent ignored, final V value, final InplaceContext inplaceContext) {
    setValueFromComponent(ignored, value);

    if(inplaceContext != null) {
      myTf.setBorder(UIUtil.getTextFieldBorder());
      if (inplaceContext.isStartedByTyping()) {
        myTf.setText(Character.toString(inplaceContext.getStartChar()));
      }
    }
    else{
      myTf.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
    }

    return myTf;
  }

    /**
     * The type My action listener.
     */
    protected final class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(final ActionEvent e){
      fireValueCommitted(true, false);
    }
  }
}
